from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Literal, Optional
from app.database import get_db
from sqlalchemy.ext.asyncio import AsyncSession

from app.schemas.activity import AdminActivityCreate, AdminActivityUpdate
from app.services.activity import ActivityService
from app.services.activity_admin import AdminActivityService
from app.models.admin import Admin
from app.api.deps import get_current_admin

router = APIRouter(prefix="/activity")


@router.get("/suggestion")
async def get_activity_suggestions(db: AsyncSession = Depends(get_db)):
    """
    主页下面推荐活动栏
    """
    try:
        service = ActivityService(db)
        result = await service.get_activity_suggestions()
        return result
    except Exception as e:
        print(e)
        raise HTTPException(status_code=500, detail={"code": 50000, "data": str(e)})



# http://localhost:8080/post/activity/filter?page=1&size=15&locations=&sort_by=1&categories&query
@router.get("/filter")
async def get_activities_filter(
    page: int = Query(1),
    size: int = Query(15),
    locations: Optional[Literal["0", "1", ""]] = Query(None),
    sort_by: Optional[Literal["0", "1", ""]] = Query(None),
    categories: Optional[str] = Query(None),
    query: Optional[str] = Query(None),
    db: Session = Depends(get_db),
):
    """获取活动列表"""
    try:
        print(page, size, locations, sort_by, categories, query)
        page = int(page)
        size = int(size)
        locations = (int(locations) if len(locations) > 0 else None) if locations else None
        sort_by = (int(sort_by) if len(sort_by) > 0 else None) if sort_by else 0
        categories = [int(i) for i in categories.split(",")] if categories else None
        query = str(query) if query else None
        print(page, size, locations, sort_by, categories, query)

        service = ActivityService(db)
        result = await service.get_activities_filter(page, size, locations, query, sort_by, categories)
        return result
    except Exception as e:
        print(e)
        raise HTTPException(status_code=500, detail={"code": 50000, "data": str(e)})


@router.get("/{id}/detail")
async def get_activity_detail(id: int, db: Session = Depends(get_db)):
    """获取活动详情"""
    try:
        service = ActivityService(db)
        result = await service.get_activity_detail(id)
        return result
    except Exception as e:
        print(e)
        raise HTTPException(status_code=500, detail={"code": 50000, "data": str(e)})


@router.get("/{id}/content")
async def get_activity_content(id: int, db: Session = Depends(get_db)):
    """获取活动内容"""
    try:
        service = ActivityService(db)
        result = await service.get_activity_content(id)
        return result
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail={"code": 50000, "data": str(e)})


@router.get("/{id}/poster")
async def get_activity_poster(id: int, db: Session = Depends(get_db)):
    """获取活动海报"""
    try:
        service = ActivityService(db)
        result = await service.get_activity_poster(id)
        return result
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail={"code": 50000, "data": str(e)})


@router.post("/create")
async def create_activity(
    activity: AdminActivityCreate,
    db: AsyncSession = Depends(get_db),
    current_admin: Admin = Depends(get_current_admin)
):
    try:
        # 1. 创建活动
        model = activity.into()
        model.publisher = current_admin.id  # 设置发布者ID
        
        # 2. 保存活动到数据库
        db.add(model)
        await db.commit()
        
        return {"code": 10000, "data": "success"}
    except Exception as e:
        await db.rollback()
        raise HTTPException(status_code=500, detail={"code": 50000, "data": str(e)})

@router.get("/get")
async def activity_get(current: int, pageSize: int, db: Session = Depends(get_db)):
    try:
        service = AdminActivityService(db)
        result = await service.get_activity(current, pageSize)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail={"code": 50000, "data": str(e)})

@router.put("/update")
async def activity_update(obj: AdminActivityUpdate, db: Session = Depends(get_db)):
    try:
        service = AdminActivityService(db)
        result = await service.update_activity(obj)
        return {"code": 10000, "data": "更新成功"}
    except Exception as e:
        raise HTTPException(status_code=500, detail={"code": 50000, "data": str(e)})

@router.delete("/delete")
async def activity_delete(
    id: int, 
    db: Session = Depends(get_db),
    current_admin: Admin = Depends(get_current_admin)
):
    try:
        service = AdminActivityService(db)
        result = await service.delete_activity(id)
        if not result:
            raise HTTPException(
                status_code=404,
                detail={"code": 40400, "data": "活动不存在"}
            )
        return {"code": 10000, "data": "删除成功"}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail={"code": 50000, "data": str(e)})
